package com.example.wln;

import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.CodingErrorAction;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.zip.GZIPInputStream;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.framework.util.MD5;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class demo {
	static String key = "18LY0316";
	static String secret = "AA610FAA3E4439CAB4A25E24AB3A14D7";
	static String url = "http://114.67.231.99/open/api/v1/items/open";
	static String shop="联韵电商";
	static Gson gson = new GsonBuilder().serializeNulls().create();

	public static void main(String[] args) throws NoSuchAlgorithmException, IOException {
		TreeMap<String, Object> systemParamMap = new TreeMap<>();
		
		
		JSONArray itemsArray = new JSONArray();

		JSONObject json = new JSONObject();
		json.put("itemID", "10001");
		json.put("shopNick",shop);
		json.put("title", "测试_匡威2018最新款帆布鞋");
		json.put("price", "398");
		json.put("quantity", "20");
		json.put("itemURL", "http://www.shijielianhe.cn/goods-info.shtml?cid=1959");
		json.put("imageURL", "http://p1k3sl4k0.bkt.clouddn.com/kjds/test/commodity/0b00f3c08da24512a07f6b994c33e1fc");
		json.put("status", "2");
		json.put("createTime", new Date());
		json.put("modifyTime", new Date());

		JSONArray skusArray = new JSONArray();
		JSONObject skus = new JSONObject();
		skus.put("skuID", "1000101");
		skus.put("itemID", "10001");
		skus.put("quantity", "20");
		skus.put("price", "398");
		skus.put("createTime", new Date());
		skus.put("modifiyTime", new Date());
		skus.put("imageURL", json.get("imageURL"));
		skus.put("status", json.get("status"));
		skus.put("attributes", "颜色:黑白;尺码:41");
		skusArray.add(skus);
		json.put("skus", skusArray);
		itemsArray.add(json);
		
		
		systemParamMap.put("app_key", key);
		systemParamMap.put("format", "json");
		
		systemParamMap.put("items", itemsArray.toJSONString());
		
		systemParamMap.put("timestamp", String.valueOf(System.currentTimeMillis()));
		
		String tmpParameter = buildParameter(systemParamMap);
		StringBuilder sign = new StringBuilder();
		sign.append(secret);
		sign.append(tmpParameter);
		sign.append(secret);
		systemParamMap.put("sign", MD5.encrytMD5(sign.toString()).toUpperCase());
		String[] strings = post(url, systemParamMap, false);
		System.out.println(strings[0]);

	}

	public static String buildParameter(TreeMap<String, Object> parameterMap, String... str) {
		StringBuffer buffer = new StringBuffer();
		for (Entry<String, Object> entry : parameterMap.entrySet()) {
			buffer.append(entry.getKey());
			if (str.length >= 1 && StringUtils.isNotBlank(str[0])) buffer.append(str[0]);
			buffer.append(entry.getValue());
			if (str.length >= 2 && StringUtils.isNotBlank(str[1])) buffer.append(str[1]);
		}
		if (str.length > 1 && StringUtils.isNotBlank(str[1])) {
			buffer.delete(buffer.length() - 1, buffer.length());
		}
		return buffer.toString();
	}

	/**
	 * 发送 POST 请求
	 * @param url 目标地址
	 * @param params 参数集
	 * @param hasFile 是否含文件
	 * @return 响应结果 [正常内容，异常内容]
	 * @throws IOException
	 */
	public static String[] post(String url, Map<String, Object> params, boolean hasFile) throws IOException {
		HttpURLConnection conn = connection(url, 5000);
		try {
			{
				StringBuilder buf = new StringBuilder(128);
				request(conn, params, 10000, buf);
			}

			{
				StringBuilder buf = null;
				String[] res = response(conn, buf);
				return res;
			}
		} finally {
			if (conn != null) conn.disconnect();
		}
	}

	/**
	 * 发送请求
	 * @param conn 连接
	 * @param params 参数集
	 * @param timeout 超时时长
	 * @param buf 请求内容缓存
	 * @param file 上传文件
	 * @throws IOException
	 */
	private static void request(HttpURLConnection conn, Map<String, Object> params, int timeout, final StringBuilder buf)
			throws IOException {
		OutputStream os = null;
		Writer writer = null;
		FileInputStream stream = null;
		try {
			conn.setRequestMethod("POST");
			conn.setReadTimeout(timeout);
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setRequestProperty("User-Agent", "Alibaba API Invoker/Java " + System.getProperty("java.version"));
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
			os = conn.getOutputStream();

			writer = new OutputStreamWriter(os, Charset.forName("utf8"));
			if (buf != null) {
				buf.append("GET ").append(conn.getURL().getPath()).append(" >> ");
				writer = new BufferedWriter(writer) {
					public Writer append(char c) throws IOException {
						buf.append(c);
						return super.append(c);
					}

					public Writer append(CharSequence csq) throws IOException {
						buf.append(csq);
						return super.append(csq);
					}
				};
			}

			if (params != null) {
				int i = 0;
				for (Iterator<Entry<String, Object>> it = params.entrySet().iterator(); it.hasNext(); it.remove(), i++) {
					Entry<String, Object> en = it.next();
					if (i > 0) writer.append('&');
					writer.append(encode(trim(en.getKey()), "utf8"));
					writer.append('=');
					writer.append(encode(trim(en.getValue()), "utf8"));
				}
			}
			writer.flush();
		} finally {
			if (writer != null) writer.close();
			if (os != null) os.close();
			if (stream != null) stream.close();
		}
	}

	/**
	 * 转换 URL 参数
	 * @param value 参数值
	 * @param charset 字符集
	 * @return 参数串
	 */
	static String encode(String value, String charset) {
		try {
			return URLEncoder.encode(value, charset);
		} catch (UnsupportedEncodingException e) {
			throw new UnsupportedOperationException();
		}
	}

	/**
	 * 修剪字符串
	 * @param content 字符串
	 * @return 修剪后字符串
	 */
	public static String trim(Object content) {
		CharSequence cs = content == null ? null : (content instanceof CharSequence) ? (CharSequence) content : String.valueOf(content);
		if (cs == null) return StringUtils.EMPTY;
		int start = 0;
		int end = cs.length() - 1;
		while (start <= end && Character.isWhitespace(cs.charAt(start)))
			start++;
		while (end >= start && Character.isWhitespace(cs.charAt(end)))
			end--;
		return cs.subSequence(start, end + 1).toString();
	}

	/**
	 * 获取连接
	 * @param url 远程应用地址
	 * @param timeout 连接时长
	 * @return 连接实例
	 * @throws IOException
	 */
	private static HttpURLConnection connection(String url, int timeout) throws IOException {
		URL u = new URL(url);

		HttpURLConnection conn = null;
		if ("https".equals(u.getProtocol())) {
			SSLContext ctx = null;
			try {
				ctx = SSLContext.getInstance("TLS");
				ctx.init(new KeyManager[0], new TrustManager[] { new X509TrustManager() {
					public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
					}

					public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
					}

					public X509Certificate[] getAcceptedIssuers() {
						return null;
					}
				} }, new SecureRandom());
			} catch (Exception e) {
				throw new IOException(e);
			}
			HttpsURLConnection connHttps = (HttpsURLConnection) u.openConnection();
			connHttps.setSSLSocketFactory(ctx.getSocketFactory());
			connHttps.setHostnameVerifier(new HostnameVerifier() {
				public boolean verify(String hostname, SSLSession session) {
					return true;// 默认都认证通过
				}
			});
			conn = connHttps;
		} else {
			conn = (HttpURLConnection) u.openConnection();
		}
		conn.setConnectTimeout(timeout);

		return conn;
	}

	/**
	 * 读取响应
	 * @param conn 连接
	 * @param buf 响应缓存
	 * @return 响应内容 [正常内容，异常内容]
	 * @throws IOException
	 */
	private static String[] response(HttpURLConnection conn, StringBuilder buf) throws IOException {
		Charset cs = charset(conn.getContentType());

		Reader reader = null;
		int index = 1;
		InputStream is = conn.getErrorStream();
		if (is == null) {
			is = conn.getInputStream();
			index = 0;
		}

		try {
			if (gzip(conn.getHeaderField("Content-Encoding"))) is = new GZIPInputStream(is);
			reader = new InputStreamReader(is,
					cs.newDecoder().onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT));
			char[] cbuf = new char[128];

			StringBuilder rbuf = new StringBuilder(128);
			if (buf != null) buf.append(conn.getURL().getPath()).append(" << ");
			for (int r = 0; (r = reader.read(cbuf)) > 0;) {
				rbuf.append(cbuf, 0, r);
				if (buf != null) buf.append(cbuf, 0, r);
			}

			String[] result = new String[2];
			result[index] = rbuf.toString();
			return result;
		} finally {
			if (is != null) is.close();
		}
	}

	/**
	 * 是否压缩
	 * @param encodings 类型
	 * @return 是、否
	 */
	private static boolean gzip(String encodings) {
		return encodings != null && encodings.indexOf("gzip") > -1;
	}

	/**
	 * 获取字符集
	 * @param ctype 内容类型
	 * @return 字符集
	 */
	private static Charset charset(String ctype) {
		Charset charset = Charset.forName("utf8");

		if (!isBlank(ctype)) {
			String[] params = ctype.split(";");
			for (String param : params) {
				param = param.trim();
				if (param.startsWith("charset")) {
					String[] pair = param.split("=", 2);
					try {
						if (pair.length >= 2 && !isBlank(pair[1])) charset = Charset.forName(pair[1].trim());
						break;
					} catch (RuntimeException e) {
					}
				}
			}
		}

		return charset;
	}

	public static boolean isBlank(String str) {
		int strLen;
		if (str != null && (strLen = str.length()) != 0) {
			for (int i = 0; i < strLen; ++i) {
				if (!Character.isWhitespace(str.charAt(i))) {
					return false;
				}
			}

			return true;
		} else {
			return true;
		}
	}

}